// ChatMessageServiceImpl.java
package com.ruoyi.chatAi.service.impl;

import com.ruoyi.chatAi.domain.ChatMessage;
import com.ruoyi.chatAi.mapper.ChatMessageMapper;
import com.ruoyi.chatAi.service.ChatMessageService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 聊天消息服务实现类
 *
 * @author ruoyi
 */
@Service
public class ChatMessageServiceImpl implements ChatMessageService {
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public ChatMessage selectChatMessageById(Long messageId) {
        return chatMessageMapper.selectChatMessageById(messageId);
    }

    @Override
    public List<ChatMessage> selectChatMessageList(ChatMessage chatMessage) {
        return chatMessageMapper.selectChatMessageList(chatMessage);
    }

    @Override
    public List<ChatMessage> selectChatMessagesBySessionId(String sessionId) {
        return chatMessageMapper.selectChatMessagesBySessionId(sessionId);
    }

    @Override
    public int insertChatMessage(ChatMessage chatMessage) {
        chatMessage.setCreateTime(DateUtils.getNowDate());
        return chatMessageMapper.insertChatMessage(chatMessage);
    }

    @Override
    public int updateChatMessage(ChatMessage chatMessage) {
        chatMessage.setUpdateTime(DateUtils.getNowDate());
        return chatMessageMapper.updateChatMessage(chatMessage);
    }

    @Override
    public int deleteChatMessageByIds(Long[] messageIds) {
        return chatMessageMapper.deleteChatMessageByIds(messageIds);
    }

    @Override
    public int deleteChatMessageById(Long messageId) {
        return chatMessageMapper.deleteChatMessageById(messageId);
    }

    @Override
    public int deleteChatMessagesBySessionId(String sessionId) {
        return chatMessageMapper.deleteChatMessagesBySessionId(sessionId);
    }

    @Override
    @Transactional
    public boolean saveConversation(String sessionId, Long userId, String userMessage, String aiReply) {
        try {
            // 保存用户消息
            ChatMessage userChatMessage = new ChatMessage();
            userChatMessage.setSessionId(sessionId);
            userChatMessage.setUserId(userId);
            userChatMessage.setRole("user");
            userChatMessage.setContent(userMessage);
            userChatMessage.setTokens(estimateTokens(userMessage));
            userChatMessage.setCreateBy(SecurityUtils.getUsername());
            userChatMessage.setCreateTime(DateUtils.getNowDate());
            chatMessageMapper.insertChatMessage(userChatMessage);

            // 保存AI回复
            ChatMessage aiChatMessage = new ChatMessage();
            aiChatMessage.setSessionId(sessionId);
            aiChatMessage.setUserId(userId);
            aiChatMessage.setRole("assistant");
            aiChatMessage.setContent(aiReply);
            aiChatMessage.setTokens(estimateTokens(aiReply));
            aiChatMessage.setCreateBy(SecurityUtils.getUsername());
            aiChatMessage.setCreateTime(DateUtils.getNowDate());
            chatMessageMapper.insertChatMessage(aiChatMessage);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<ChatMessage> getConversationContext(String sessionId, int maxContextSize) {
        ChatMessage queryParam = new ChatMessage();
        queryParam.setSessionId(sessionId);
        List<ChatMessage> allMessages = chatMessageMapper.selectChatMessageList(queryParam);

        if (allMessages.size() <= maxContextSize) {
            return allMessages;
        }

        return allMessages.subList(allMessages.size() - maxContextSize, allMessages.size());
    }

    @Override
    public int countUserMessages(Long userId) {
        return chatMessageMapper.countUserMessages(userId);
    }

    @Override
    public int estimateTokens(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }
        // 简单估算：英文单词约1.3个token，中文字符约1个token
        return (int)(text.length() * 1.3);
    }
}